// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const setting = await db.collection('Setting').doc('5a93cec95edf0fc400679b4f23f37a84').get()
  const {
    _id,
    message,
    treasures
  } = event
  switch (event.op) {
    case 'getBox':
      return getBox();
      break;
    case 'openBox':
      return openBox();
      break;
    case 'hideBox':
      return hideBox();
      break;
    case 'updateOpenTimes':
      return updateOpenTimes();
      break;

  }



  async function getBox() {

    let treasures = setting.data.treasures

    let result = await db.collection('Box')
      .aggregate()
      .match({
        status: 0
      })
      .sample({
        size: 9
      })
      .lookup({
        from: 'User',
        localField: '_openid',
        foreignField: '_openid',
        as: 'user',
      })
      .end()
    let res1 = result.list

    //如果数量不够，自动补齐
    let len = 9 - res1.length
    let users = [{
      nickname: '清芷',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/1.jpg'
    }, {
      nickname: '彬蔚',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/2.jpg'
    }, {
      nickname: '语秋',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/3.jpg'
    }, {
      nickname: '浦深',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/4.jpg'
    }, {
      nickname: '知许',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/5.jpg'
    }, {
      nickname: '清芷',
      avatar: 'cloud://wedaily-6iwce.7765-wedaily-6iwce-1301301505/userAvatar/6.jpg'
    }]
    for (let i = 0; i < len; i++) {
      let officalItem = {}
      let treasure = treasures[Math.floor(Math.random() * 6)]
      treasure.amount = 1
      let ts = []
      ts.push(treasure)
      officalItem.treasures = ts
      officalItem.user = [users[Math.floor(Math.random() * 6)]]
      res1.push(officalItem)
    }
    for (let i = 0; i < res1.length; i++) {
      let tempUser = {}
      tempUser.nickname = res1[i].user[0].nickname
      tempUser.avatar = res1[i].user[0].avatar
      tempUser._openid = res1[i].user[0]._openid
      res1[i].user = tempUser
      for (let j = 0; j < res1[i].treasures.length; j++) {

        for (let k = 0; k < treasures.length; k++) {
          if (res1[i].treasures[j].type == treasures[k].type) {
            res1[i].treasures[j].title = treasures[k].title
            res1[i].treasures[j].price = treasures[k].price
            res1[i].treasures[j].src = treasures[k].src
          }
        }
      }
    }
    return res1

  }
  async function openBox() {
    let maxOpenBoxTimes = setting.data.maxOpenBoxTimes
    let res = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).get()
    if (res.data[0].openBoxTimes >= maxOpenBoxTimes) {
      return 'notEnough'
    }

    let awardGold = 0

    let treasureAmount = 0
    for (let i = 0; i < treasures.length; i++) {
      treasureAmount += treasures[i].amount
    }

    if (_id) {
      let box = await db.collection('Box').doc(_id).get()

      if (box.data.status == 0) {
        await db.collection('Box').doc(_id)       
          .update({
            data: {
              status: 1,
              foundid: wxContext.OPENID
            },
          })
        if (box.data._openid == wxContext.OPENID) {
          awardGold = treasureAmount * 100
        }
      } else {
        return "openedByOthers"
      }
    }
    //
    await db.collection('User').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
        openBoxTimes: _.inc(1),
        gold: _.inc(awardGold),    
        active: _.inc(1),
      }
    })

    //

    for (let i = 0; i < treasures.length; i++) {
      let item = treasures[i]
      let treasure = await db.collection("Treasure").where({
        _openid: wxContext.OPENID,
        type: item.type
      }).get()

      if (treasure.data.length == 0) {
        await db.collection('Treasure').add({
          data: {
            type: item.type,
            amount: item.amount,
            _openid: wxContext.OPENID,
          }
        })
      } else {
        await db.collection('Treasure').where({
          _openid: wxContext.OPENID,
          type: item.type
        }).update({
          data: {
            amount: _.inc(parseInt(item.amount))
          }
        })
      }
    }
    //

    //
    await db.collection('Record').add({
      data: {
        createTime: db.serverDate(),
        content: {
          op: 'openBox',
          treasureAmount: treasureAmount,
          boxid: _id ? _id : 'null'
        },
        _openid: wxContext.OPENID,
      }
    })
    return 'saved'

  }
  async function hideBox() {
    //更新玩家的宝物库
    let treasureAmount = 0
    for (let i = 0; i < treasures.length; i++) {
      await db.collection("Treasure").doc(treasures[i]._id).update({
        data: {
          amount: _.inc(-treasures[i].amount)
        }
      })
      treasureAmount += treasures[i].amount
      delete treasures[i]._id
    }
   
    //新增宝箱
    let res = await db.collection("Box").add({
      data: {
        treasures: treasures,
        _openid: wxContext.OPENID,
        message: message,
        create_time: db.serverDate(),
        status: 0, //初始状态未打开
      }
    })
    //用户活跃值+2
    await db.collection('User').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
     
        active: _.inc(2),
      }
    })
    //生成消息
    await db.collection('Record').add({
      data: {
        createTime: db.serverDate(),
        content: {
          op: 'hideBox',
          treasureAmount: treasureAmount,
          boxid: res._id
        },
        _openid: wxContext.OPENID,
      }
    })
    return res
  }

  async function updateOpenTimes() {
    let res = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        gold:_.inc(-300),
        openBoxTimes: setting.data.maxOpenBoxTimes - setting.data.awardOpenBoxTimes
      }
    })
    return res
  }


}